package com.example.woh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.woh.entity.BO.HomeworkBO;
import com.example.woh.entity.BO.QuestionBO;
import com.example.woh.entity.Homework;
import com.example.woh.entity.Question;
import com.example.woh.entity.Submit;
import com.example.woh.entity.User;
import com.example.woh.service.IHomeworkService;
import com.example.woh.service.IQuestionService;
import com.example.woh.service.ISubmitService;
import com.example.woh.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sail
 * @since 2023-03-24
 */
@RestController
@RequestMapping("/homework")
@RequiredArgsConstructor
public class HomeworkController {

    private final IQuestionService questionService;
    private final IHomeworkService homeworkService;
    private final ISubmitService submitService;
    private final IUserService userService;

    @GetMapping("/get/{id}")
    public ResponseEntity<List<Homework>> get(@PathVariable String id){
        String classId = userService.getById(id).getClassId();
        List<Homework> homeworkList = homeworkService.queryByClassId(classId);
        for (Homework h : homeworkList) {
            h.setQuestionList(questionService.queryByHomeworkId(h.getId()));
        }
        return ResponseEntity.ok(homeworkList);
    }

    @PostMapping("/publish")
    @ResponseBody
    public ResponseEntity<String> publish(@RequestBody HomeworkBO homeworkBO){
        //System.out.println(homeworkBO);
        int homeworkId = homeworkService.saveHomework(homeworkBO);

        List<Question> questionList = new ArrayList<>();
        for (QuestionBO questionBO : homeworkBO.getQuestionList()) {
            Question question = new Question();
            BeanUtils.copyProperties(questionBO,question);
            question.setHomeworkId(homeworkId);
            questionList.add(question);
        }
        questionService.saveBatch(questionList);

        List<Submit> submitList = new ArrayList<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id",homeworkBO.getClassId()).eq("identity",2);
        List<User> userList = userService.list(queryWrapper);
        for (User user : userList) {
            Submit submit = new Submit();
            submit.setUserId(user.getId());
            submit.setHomeworkId(homeworkId);
            submitList.add(submit);
        }
        submitService.saveBatch(submitList);

        return ResponseEntity.ok("成功");
    }


}
